package com.weiz.designpatterns.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
class CharacterFactory {
    private static Map<Character, ICharacter> chs = new HashMap<Character, ICharacter>();
    private static CharacterFactory instance = new CharacterFactory();
    // 单例模式
    private CharacterFactory() {
    };

    /**
     * Checked the character whether existed or not,if the character existed, then directly returns,
     otherwise, instantiates a character object.
     * @param key
     * @return
     */
    public ICharacter getCharacter(Character key) {

        ICharacter character = null;

        if (chs.containsKey(key)) {
            character = chs.get(key);
        } else {
            switch (key.charValue()) {
                case 'A':
                    character = new CharacterA();
                    break;
                case 'B':
                    character = new CharacterB();
                    break;
                case 'C':
                    character = new CharacterC();
                    break;
                default:
                    break;
            }
            chs.put(key, character);
        }
        return character;
    }

    public static CharacterFactory getInstance() {
        return instance;
    }
}